// /*
//  * This file is part of the microblog <http://code.google.com/p/froggymicroblog/>
//  *
//  * Copyright (c) 2009, bouleetbil  <bouleetbil@frogdev.info>
//  * All rights reserved.
//  * 
//  * Redistribution and use in source and binary forms, with or without modification, are 
//  * permitted provided that the following conditions are met:
//  *
//  * - Redistributions of source code must retain the above copyright notice, this list 
//  *   of conditions and the following disclaimer.
//  * - Redistributions in binary form must reproduce the above copyright notice, this list 
//  *   of conditions and the following disclaimer in the documentation and/or other 
//  *   materials provided with the distribution.
//  * - Neither the name of the Twitterizer nor the names of its contributors may be 
//  *   used to endorse or promote products derived from this software without specific 
//  *   prior written permission.
//  *
//  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
//  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
//  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
//  * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
//  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
//  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
//  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
//  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
//  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
//  * POSSIBILITY OF SUCH DAMAGE.
//  */



using System;
using System.Threading;
using System.Diagnostics;
using Gtk;
using Gdk;
using System.Collections.Generic;
using System.Collections;
using Twitter;
using Metier;
using Gconf;


namespace FrogMicroBlog
{
	
	
	public partial class Fen_Principal : Gtk.Window
	{
		private const string MicroBlogVersion=" 0.1.2.5";
		private TwitterObject MonTwitter;
		private IdentiObject MonIdenti;
		private ListStore TwitListStore;
		private System.Timers.Timer Clock;
		private Thread oThread;
		private Conf MyConf = new Conf();
		public UrlLabel urllabel = new UrlLabel();
		

		//status icon
 		private StatusIcon statusIcon;
		
		protected Gtk.TreeIter iter;
		private ArrayList treeMessages;	
		
		public Fen_Principal() : 
				base(Gtk.WindowType.Toplevel)
		{
			this.Build();
			InitFen();
			//affichage
			pAffichage();
		
		}
		private void InitFen()
		{
			vbox4.Add(urllabel);
			urllabel.LineWrap = true;
			urllabel.Selectable = true;
			urllabel.Xalign = 0.0f;
			urllabel.Yalign = 0.0f;
			urllabel.WidthRequest = 100;
			urllabel.Markup = String.Format("<span foreground='#204a87'>{0}</span>",
				"");
			urllabel.Show();
			
			urllabel.UrlActivated += delegate(object o, UrlActivatedArgs args) {
				Outils.OpenLink(args.Url);
			};
			
			
			
			//récupérer les paramétres enegistés
			MyConf.LoadConfig();
			this.Title="MicroBlog Version"+MicroBlogVersion;
			SAI_LoginTwitter.Text=MyConf.NameTwitter;
			SAI_PassTwitter.Text=MyConf.PassTwitter;

			SAI_LoginIdenti.Text=MyConf.NameIdenti;
			SAI_PassIdenti.Text=MyConf.PassIdenti;

			if (Convert.ToInt32(MyConf.Time)>3)
			{
				SPINtps.Value=Convert.ToInt32(MyConf.Time);
			}

			//création du timer de raffraichissement
			//5000 milliseconds (5 seconds)
			Clock=new System.Timers.Timer();
			Clock.Elapsed += new System.Timers.ElapsedEventHandler(HandleElapsed);
			Clock.Interval=SPINtps.Value*60000;
	    	Clock.Start();
		

			//création d'un compte identi.ca
			MonIdenti = new IdentiObject(SAI_LoginIdenti.Text,SAI_PassIdenti.Text);
		
			//création d'un twitter
			MonTwitter = new TwitterObject(SAI_LoginTwitter.Text,SAI_PassTwitter.Text);

			IMG_pseudo.Pixbuf=Download.DonwloadImage(MonTwitter.User.Image,MonTwitter.User.Nom,MonTwitter.User.Password);

			IMG_Identi.Pixbuf=Download.DonwloadImage(MonIdenti.User.Image,MonIdenti.User.Nom,MonIdenti.User.Password);
			
		}
		/// <summary>
		/// handle du timer
		/// </summary>
		/// <param name="sender">
		/// A <see cref="System.Object"/>
		/// </param>
		/// <param name="e">
		/// A <see cref="System.Timers.ElapsedEventArgs"/>
		/// </param>
		void HandleElapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
			pRempliTwit();
		}
		private void pRempliTwit()
		{
				if(oThread != null) {
				oThread.Abort();
				oThread=null;
			}
			oThread = new Thread(new ThreadStart(this.RefreshThread));
			// Start the thread
	      	oThread.Start();
		}
		public void RefreshThread(){
			
				//Console.WriteLine("Récupération nouveau twit");
				twitrefresh();
			
		}
		
		/// <summary>
		/// Gestion affichage
		/// </summary>
		public void pAffichage(){
			
			//icon
			//status icon
		
			// Creation of the Icon
			statusIcon = new StatusIcon(new Pixbuf (null,"microblog.png"));
			statusIcon.Visible = true;
			// Show/Hide the window (even from the Panel/Taskbar) when the TrayIcon has been clicked.
			statusIcon.Activate += delegate { this.Visible = !this.Visible; };
			// Show a pop up menu when the icon has been right clicked.
			statusIcon.PopupMenu += OnTrayIconPopup;
	 
			// A Tooltip for the Icon
			statusIcon.Tooltip = this.Title;
			
			// Event on treeview
			TRE_Twit.Selection.Changed += OnSelectionEntry;
			
			this.SAI_PassTwitter.Visibility=false;
			this.SAI_PassIdenti.Visibility=false;
			
			//TwitListStore = new Gtk.ListStore (typeof (Gdk.Pixbuf),
			//	typeof (string),  typeof (string),  typeof (string),  typeof (string));
			TwitListStore = new Gtk.ListStore (typeof (TreeMessage));
			
			//pour l'icone
			Gtk.TreeViewColumn TwitColumnIcon = new Gtk.TreeViewColumn ();
			TwitColumnIcon.Title = "Icon";
			Gtk.CellRendererPixbuf TwitCellIcon = new Gtk.CellRendererPixbuf ();
			TwitColumnIcon.PackStart (TwitCellIcon, true);
			TwitColumnIcon.SetCellDataFunc (TwitCellIcon, new Gtk.TreeCellDataFunc(RenderIcon));	
			
			//pour le pseudo
			Gtk.TreeViewColumn TwitColumnPseudo = new Gtk.TreeViewColumn ();
			TwitColumnPseudo.Title = "Pseudo";
			Gtk.CellRendererText TwitCellPseudo = new Gtk.CellRendererText ();
			TwitColumnPseudo.PackStart (TwitCellPseudo, true);
			TwitColumnPseudo.SetCellDataFunc (TwitCellPseudo, new Gtk.TreeCellDataFunc(RenderPseudo));	
			
			//pour le message
			Gtk.TreeViewColumn TwitColumn = new Gtk.TreeViewColumn ();
			TwitColumn.Title = "Twit";
			Gtk.CellRendererText TwitCell = new Gtk.CellRendererText ();
			TwitColumn.PackStart (TwitCell, true);
			TwitColumn.SetCellDataFunc (TwitCell, new Gtk.TreeCellDataFunc(RenderMessage));	
			
			//pour la date
			Gtk.TreeViewColumn TwitColumnDate = new Gtk.TreeViewColumn ();
			TwitColumnDate.Title = "Date";
			Gtk.CellRendererText TwitCellDate = new Gtk.CellRendererText ();
			TwitColumnDate.PackStart (TwitCellDate, true);
			TwitColumnDate.SetCellDataFunc (TwitCellDate, new Gtk.TreeCellDataFunc(RenderDate));	

			//pour l'id
			Gtk.TreeViewColumn TwitColumnId = new Gtk.TreeViewColumn ();
			TwitColumnId.Title = "Id";
			Gtk.CellRendererText TwitCellId = new Gtk.CellRendererText ();
			TwitColumnId.PackStart (TwitCellId, true);
			TwitColumnId.SetCellDataFunc (TwitCellId, new Gtk.TreeCellDataFunc(RenderId));
			
			//type de message
			Gtk.TreeViewColumn TwitColumnType = new Gtk.TreeViewColumn ();
			TwitColumnType.Title = "Type";
			Gtk.CellRendererText TwitCellType = new Gtk.CellRendererText ();
			TwitColumnType.PackStart (TwitCellType, true);
			TwitColumnType.SetCellDataFunc (TwitCellType, new Gtk.TreeCellDataFunc(RenderType));
			
			TRE_Twit.AppendColumn(TwitColumnIcon);
			//TRE_Twit.AppendColumn ("Icon", new Gtk.CellRendererPixbuf (), "pixbuf", 0);

			TRE_Twit.AppendColumn(TwitColumnDate);
			//TRE_Twit.AppendColumn ("Date", new Gtk.CellRendererText (), "text", 1);
			
			TRE_Twit.AppendColumn(TwitColumnPseudo);
			//TRE_Twit.AppendColumn ("Pseudo", new Gtk.CellRendererText (), "text", 2);
			
			TRE_Twit.AppendColumn(TwitColumn);
			//TRE_Twit.AppendColumn ("Twit", new Gtk.CellRendererText (), "text", 3);

			TRE_Twit.AppendColumn(TwitColumnId);
			//TRE_Twit.AppendColumn ("id", new Gtk.CellRendererText (), "text", 4);

			//type des messages
			TRE_Twit.AppendColumn(TwitColumnType);
			
			TRE_Twit.Columns[1].Visible=false;
			//pour stocker les identifiants des twits
			TRE_Twit.Columns[4].Visible=false;
			
			
			try{
			pRempliTwit();
			}
			catch{}
			
		}

	// Create the popup menu, on right click.
	static void OnTrayIconPopup (object o, EventArgs args) {
		Menu popupMenu = new Menu();
		ImageMenuItem menuItemQuit = new ImageMenuItem ("Quit");
		Gtk.Image appimg = new Gtk.Image(Stock.Quit, IconSize.Menu);
		menuItemQuit.Image = appimg;
		popupMenu.Add(menuItemQuit);
		// Quit the application when quit has been clicked.
		menuItemQuit.Activated += delegate { Application.Quit(); };
		popupMenu.ShowAll();
		popupMenu.Popup();
	}
		
	/// <summary>
	/// Event for treeview
	/// </summary>
	/// <param name="o">
	/// A <see cref="System.Object"/>
	/// </param>
	/// <param name="args">
	/// A <see cref="EventArgs"/>
	/// </param>
	protected void OnSelectionEntry(object o, EventArgs args)
	    {
	        TreeModel model;
	   		try{
		        if (((TreeSelection)o).GetSelected(out model, out iter))
		        {
		            
		            TreeMessage T =(TreeMessage)model.GetValue (iter, 0);
					//TextMessage.Buffer.Text=T.Message;
					string text =T.Message;
					//call url detection
					text = Outils.UrlDetection(text,T.Type);
		            text = text.Replace("&amp;lt;", "&lt;");
					text = text.Replace("&amp;gt;", "&gt;");
					urllabel.Markup = "<span foreground='#204a87'>" + text + "</span>";
					IMGUser.Pixbuf=T.Image;
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex.Message.ToString());
			}
	    }


		
		public void pTreeview()
		{
			Gtk.Application.Invoke (delegate {
			BTN_Refresh.Sensitive=false;
			TwitListStore.Clear();
			
			treeMessages = new ArrayList(20);
			
			
			//twitter	
			// Add some data to the store
			int NbTwit=MonTwitter.NbTwit;
			Message UnTwit;
			for (int cpt = NbTwit-1; cpt>-1;cpt--)
			{
				try{
				UnTwit=MonTwitter.GetUnTwit(cpt);
				treeMessages.Add(new TreeMessage(UnTwit.User.Logo,UnTwit.Date,UnTwit.User.Pseudo,UnTwit.Texte,cpt.ToString(),"twitter.com"));
				}
				catch{}
			}
			//identi.ca
			int NbMessageIdenti=MonIdenti.NbTwit;
			Message UnMessage;
			for (int cptmessage = NbMessageIdenti-1; cptmessage>-1;cptmessage--)
			{
				try{
					UnMessage=MonIdenti.GetUnMessage(cptmessage);
					//Console.WriteLine(UnMessage.Texte);
					//Console.WriteLine(UnMessage.Date,UnMessage.User.Pseudo,UnMessage.Texte,"","identi.ca");
					TreeMessage Mess = new TreeMessage(UnMessage.User.Logo,UnMessage.Date,UnMessage.User.Pseudo,UnMessage.Texte,cptmessage.ToString(),"identi.ca");
					treeMessages.Add(Mess);
				}
				catch(Exception ex)
				{
						Console.WriteLine(ex.Message.ToString());
				}
			}
			
			treeMessages.Sort();

				                  
			foreach (TreeMessage treemessage in treeMessages) {
					try{
						TwitListStore.AppendValues (treemessage);
					}
					catch
					{
					}
			}
			
			TRE_Twit.Model = TwitListStore;
	
			BTN_Refresh.Sensitive=true;
			});
	       
			
		}
		private void RenderMessage (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
		{
			
			TreeMessage message = (TreeMessage) model.GetValue (iter, 0);
			string pseudo1=MonTwitter.User.Pseudo;
			string pseudo2=MonIdenti.User.Pseudo;
			string MessageCourant=message.Message;

			(cell as Gtk.CellRendererText).Foreground = "black";
			if (pseudo1!="")
			{
				if (MessageCourant.IndexOf(pseudo1) != -1) {
					(cell as Gtk.CellRendererText).Foreground = "red";
				} 
			}
			if (pseudo2!="")
			{
				if (MessageCourant.IndexOf(pseudo2) != -1) {
					(cell as Gtk.CellRendererText).Foreground = "red";
				}
			}
			(cell as Gtk.CellRendererText).Text = message.Message;
			
		}
		private void RenderPseudo (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
		{
			
			TreeMessage message = (TreeMessage) model.GetValue (iter, 0);
			(cell as Gtk.CellRendererText).Text = message.Pseudo;
		}

		private void RenderDate (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
		{
			
			TreeMessage message = (TreeMessage) model.GetValue (iter, 0);
			(cell as Gtk.CellRendererText).Text = message.Date;
		}
		private void RenderId (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
		{
			
			TreeMessage message = (TreeMessage) model.GetValue (iter, 0);
			(cell as Gtk.CellRendererText).Text = message.Id;
		}
		private void RenderType (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
		{
			
			TreeMessage message = (TreeMessage) model.GetValue (iter, 0);
			(cell as Gtk.CellRendererText).Text = message.Type;
		}
		private void RenderIcon (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
		{
			
			TreeMessage message = (TreeMessage) model.GetValue (iter, 0);
			(cell as Gtk.CellRendererPixbuf).Pixbuf = message.Image;
		}

		
		protected void OnDeleteEvent (object sender, DeleteEventArgs a)
		{
			//on masque la fenêtre
			this.Hide();
			a.RetVal = true;
		}
	
		protected virtual void EventEnregConf (object sender, System.EventArgs e)
		{
			MyConf.NameTwitter=SAI_LoginTwitter.Text;
			MyConf.PassTwitter=SAI_PassTwitter.Text;
			MyConf.NameIdenti=SAI_LoginIdenti.Text;
			MyConf.PassIdenti=SAI_PassIdenti.Text;
			MyConf.Time=SPINtps.Value.ToString();
			MyConf.SaveConfig();
			//on raffraichit la liste des twits
			InitFen();
			pRempliTwit();
		}
	
		protected virtual void pTexteChange (object sender, System.EventArgs e)
		{
			LAB_twit.Text=SAI_Post.Text.Length.ToString()+"/140";
		}
	
		protected virtual void pRefresh (object sender, System.EventArgs e)
		{
			twitrefresh();
			
		}
		public void twitrefresh(){
			
			MonTwitter.GetTwitts();
			MonIdenti.GetMessages();
			pTreeview();
		}
	
		protected virtual void BTN_SendTwitterClick (object sender, System.EventArgs e)
		{
			SendTwit();
		}	
	
	
		protected virtual void pKeyRelache (object o, Gtk.KeyReleaseEventArgs args)
		{
			if (args.Event.Key.ToString()=="Return")
			{
				SendTwit();
			}
		}
		
		private void SendTwit()
		{
			
			if (SAI_Post.Text.Length>0)
			{
				Console.WriteLine("Envoi twit");
				MonTwitter.SendText(SAI_Post.Text);
				System.Threading.Thread.Sleep(1000);
				twitrefresh();
				SAI_Post.Text="";
			}
			
		}
		protected virtual void pKeyRelacheIdenti (object o, Gtk.KeyReleaseEventArgs args)
		{
			if (args.Event.Key.ToString()=="Return")
			{
				SendIdenti();
			}
		}
		private void SendIdenti()
		{
			
			if (SAI_PostIdenti.Text.Length>0)
			{
				Console.WriteLine("Envoi identi");
				MonIdenti.SendText(SAI_PostIdenti.Text);
				System.Threading.Thread.Sleep(1000);
				twitrefresh();
				SAI_PostIdenti.Text="";
			}
			
		}
		protected virtual void BTN_SendIdentiClick (object sender, System.EventArgs e)
		{
			SendIdenti();
		}

		protected virtual void OnSAIPostIdentiChanged (object sender, System.EventArgs e)
		{
			LAB_identi.Text=SAI_PostIdenti.Text.Length.ToString()+"/140";
		}

		protected virtual void OnButtonSiteClicked (object sender, System.EventArgs e)
		{
			Outils.OpenLink("http://code.google.com/p/froggymicroblog/");
		}		

		
		
	
	}

}


		
	

